import { WXIconType } from "../../../wxAPI_";
import * as NS from "../../../Common/NetServices";
import { IsNull } from "../../../TYLibrary/Common/GlobalExtend";
import { Wx_XSPPage, V_Product, V_Cart, V_ShoppingCartHelper } from "../../../Common/Entitys";
import { Log } from "../../../TYLibrary/System/Logger";
import { Wx_PageData, WXDataClassRuntimeDecorator } from "../../../Common/EntityBase";

@WXDataClassRuntimeDecorator()
class ShoppingCartPageData extends Wx_PageData {
    public List: Array<V_ShoppingCartHelper> = [];
    public TotalPrice: string = "";
    public AllSelected: boolean = false;
    public Count: number = 1;
    public IsDisable: boolean = true;
    public flag: boolean = false;
}

class IndexPage extends Wx_XSPPage {
    public Data: ShoppingCartPageData = new ShoppingCartPageData();

    /**
     *
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async onShowAgain(): Promise<void> {
        this.InitData(null);
    }

    /**
     * 初始化页面信息
     * @param {any} options
     * @returns {Promise<void>}
     * @memberof IndexPage
     */

    public async InitData(options: any): Promise<void> {
        try {
            wx.showToast({
                title: "数据加载中.....",
                icon: WXIconType.loading
            });
            // 底部加载
            this.EditTabBar();
            // let list = await NS.QueryShoppingCart(this.App.OpenID);
            // await this._SetData({ List: list });
            // this.data.flag = false;
            wx.hideToast();
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 复选框事件 店铺
     * @param {any} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async ShopCheckboxChangeHandler(e: any): Promise<void> {
        try {
            const id = e.currentTarget.dataset.shopid;
            let dList = this.Data.List;
            let shop = dList.Default(item => {
                return item.ShopID == id;
            });
            if (IsNull(shop)) return;
            let selected = true;
            if (e.detail.value.length == 0 || e.detail.value[0] != id) selected = false;
            shop.Selected = selected;
            if (!IsNull(shop))
                shop.Products.ForEach((item, index) => {
                    item.Selected = selected;
                });

            this.Data.List = dList;
            await this.Data.ApplyChange(this);
            this._SalePriceAndRefreshState();
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 编辑商品信息
     * @param {any} e
     * @returns {void}
     * @memberof IndexPage
     */
    public EidtShopProductHandler(e: any): void {
        try {
            const id = e.currentTarget.dataset.shopid;
            let dList = this.Data.List;
            let shop = dList.Default(item => {
                return item.ShopID == id;
            });
            if (IsNull(shop)) return;
            shop.EditVisable = true;
            if (!IsNull(shop))
                // shop.Products.ForEach((item, index) => { item.EditVisable = true; });
                this.Data.List = dList;
            this.Data.ApplyChange(this);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 完成商品修改
     * @param {any} e
     * @returns {void}
     * @memberof IndexPage
     */
    public FinishEditShopProductHandler(e: any): void {
        try {
            const id = e.currentTarget.dataset.shopid;
            let dList = this.Data.List;
            let shop = dList.Default(item => {
                return item.ShopID == id;
            });
            if (IsNull(shop)) return;
            shop.EditVisable = false;
            if (!IsNull(shop))
                // shop.Products.ForEach((item, index) => { item.EditVisable = false; });
                this.Data.List = dList;
            this.Data.ApplyChange(this);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 删除商品
     * @param {any} e
     * @returns { Promise<void>}
     * @memberof IndexPage
     */
    public async DeleteProductHandler(e: any): Promise<void> {
        try {
            const id = e.currentTarget.dataset.id;
            let dList = this.Data.List;

            let p: V_Cart = null;
            let shop: V_ShoppingCartHelper = null;
            dList.ForEach((item, index) => {
                p = item.Products.Default(item1 => {
                    return item1.ID == id;
                });
                if (!IsNull(p)) {
                    shop = item;
                    return true;
                } else return false;
            });
            if (!IsNull(p)) {
                await NS.DeleteCart(p.ID);

                shop.Products.Remove(p);
                this.Data.List = dList;
                this.Data.ApplyChange(this);
                this._SalePriceAndRefreshState();
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 减少商品数量
     * @param {any} e
     * @returns { Promise<void>}
     * @memberof IndexPage
     */
    public async DecreaseCountHandler(e: any): Promise<void> {
        try {
            /*   const id = e.currentTarget.dataset.id;
              let dList = this.data.List;
  
              let p: V_Cart = null;
              dList.ForEach((item, index) => {
                  p = item.Products.Default((item1) => { return item1.ID == id })
                  if (!IsNull(p))
                      return true;
                  else
                      return false;
              });
              if (!IsNull(p)) {
                  if (p.PRODUCTCOUNT > 1)
                      p.PRODUCTCOUNT--;
                  await NS.UpdateCartCount(p);
                  await this._SetData({ List: dList, });
                  this._SalePriceAndRefreshState();
              } */
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 增加商品数量
     * @param {any} e
     * @returns { Promise<void>}
     * @memberof IndexPage
     */
    public async IncreaseCountHandler(e: any): Promise<void> {
        try {
            /*    const id = e.currentTarget.dataset.id;
               let dList = this.data.List;
   
               let p: V_Cart = null;
               dList.ForEach((item, index) => {
                   p = item.Products.Default((item1) => { return item1.ID == id })
                   if (!IsNull(p))
                       return true;
                   else
                       return false;
               });
               if (!IsNull(p)) {
                   //缺少判断库存
                   p.PRODUCTCOUNT++;
                   console.log(p);
                   await NS.UpdateCartCount(p);
                   console.log(p);
                   await this._SetData({ List: dList });
                   this._SalePriceAndRefreshState();
               } */
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 复选框事件 商品
     * @param {any} e
     * @returns { Promise<void>}
     * @memberof IndexPage
     */
    public async ProductCheckboxChange(e: any): Promise<void> {
        try {
            const id = e.currentTarget.dataset.id;
            let dList = this.Data.List;

            let p: V_Cart = null;
            let shop: V_ShoppingCartHelper;
            dList.ForEach((item, index) => {
                p = item.Products.Default(item1 => {
                    return item1.ID == id;
                });
                if (!IsNull(p)) {
                    shop = item;
                    return true;
                } else return false;
            });
            if (!IsNull(p)) {
                let selected = true;
                if (e.detail.value.length == 0 || e.detail.value[0] != id) selected = false;
                p.Selected = selected;

                let shopSelected = false;
                shop.Products.ForEach((item, index) => {
                    if (item.ID != id && item.Selected == true) {
                        shopSelected = true;
                        return true;
                    }
                });
                shop.Selected = shopSelected || selected;
                this.Data.List = dList;
                await this.Data.ApplyChange(this);
                this._SalePriceAndRefreshState();
            }
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     * 结算
     * @param {*} e
     * @memberof IndexPage
     */
    public SettlementHandler(e: any): void {
        try {
            this.BuildingHandler(e);
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     *
     * @private
     * @memberof IndexPage
     */
    private _SalePriceAndRefreshState(): void {
        let t = 0;
        let allSelected = true;
        this.Data.List.ForEach((item, index) => {
            let shopSelected = false;
            let allproductSelected = true;
            item.Products.ForEach((item1, index1) => {
                if (item1.Selected) {
                    // t += item1.OLD_PRODUCTPRICE * item1.PRODUCTCOUNT;
                    shopSelected = true;
                } else allproductSelected = false;
            });
            item.Selected = shopSelected;
            if (!allproductSelected) allSelected = false;
        });
        this.Data.TotalPrice = t.toFixed(2);
        this.Data.AllSelected = allSelected;
        this.Data.ApplyChange(this);
    }

    /**
     * 全选
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async AllCheckboxChange(e: any): Promise<void> {
        try {
            let dList = this.Data.List;
            let selected = true;
            if (e.detail.value.length == 0 || e.detail.value[0] != "all") selected = false;
            dList.forEach((item, index) => {
                item.Selected = selected;
                item.Products.ForEach((item1, index1) => {
                    item1.Selected = selected;
                });
            });
            this.Data.List = dList;
            await this.Data.ApplyChange(this);
            this._SalePriceAndRefreshState();
        } catch (e) {
            this.ShowError(e);
        }
    }

    /**
     *
     * @param {*} e
     * @memberof IndexPage
     */
    public NumberHandler(e: any): void {
        let type = e.currentTarget.dataset.type;
        if (type == 0) {
            if (this.Data.Count == 2) {
                this.Data.IsDisable = true;
                this.Data.Count = 1;
                this.Data.ApplyChange(this);
            } else {
                if (this.Data.Count > 1) this.Data.Count--;
                this.Data.ApplyChange(this);
            }
        } else {
            this.Data.Count++;
            this.Data.IsDisable = false;
            this.Data.ApplyChange(this);
        }
    }

    /**
     * 编辑
     * @param {*} e
     * @memberof IndexPage
     */
    public EditHandler(e: any): void {
        if (this.Data.flag == false) {
            this.Data.flag = true;
            this.Data.ApplyChange(this);
        }
    }

    /**
     * 完成
     * @param {*} e
     * @memberof IndexPage
     */
    public FinishHandler(e: any): void {
        if (this.Data.flag == true) {
            this.Data.flag = false;
            this.Data.ApplyChange(this);
        }
    }

    /**
     * 清空失效
     * @param {*} e
     * @memberof IndexPage
     */
    public EmptyHandler(e: any): void {
        wx.showModal({
            title: "提示",
            content: "确认清空失效商品吗？",
            success: function(res) {
                if (res.confirm) {
                    console.log("用户点击确定");
                } else if (res.cancel) {
                    console.log("用户点击取消");
                }
            }
        });
    }

    /**
     * 删除商品
     * @param {*} e
     * @memberof IndexPage
     */
    public DelHandler(e: any): void {
        try {
            wx.showModal({
                title: "提示",
                content: "确认删除该商品吗？",
                success: function(res) {
                    if (res.confirm) {
                        console.log("用户点击确定");
                    } else if (res.cancel) {
                        console.log("用户点击取消");
                    }
                }
            });
        } catch (e) {}
    }

    /**
     *
     * @param {*} e
     * @memberof IndexPage
     */
    public AllcheckboxHandler(e: any): void {
        let s = e.detail.value;
        console.log(e, s, "ssssssssssssssssssssssssssssssssssssssssssss");
    }

    /**
     * 结算
     * @param {*} e
     * @memberof IndexPage
     */
    public AccountHandler(e: any): void {
        try {
            //     let type = e.currentTarget.dataset.type;
            //     let id = e.currentTarget.dataset.id;
            //     let cardbill = e.currentTarget.dataset.cardbill;
            console.log(e, "ssssssssssssssssssssssssssssssssssssssssssss");
            wx.navigateTo({
                url: "../FirmOrder/Index"
            });
        } catch (e) {}
    }

    /**
     *
     * @param {*} e
     * @returns {Promise<void>}
     * @memberof IndexPage
     */
    public async NxetHandler(e: any): Promise<void> {
        try {
            let type = e.currentTarget.dataset.type;
            let id = e.currentTarget.dataset.id;
            let cardbill = e.currentTarget.dataset.cardbill;
            wx.navigateTo({
                url: "../ProductClass/Product"
            });
        } catch (e) {}
    }
}

Page(new IndexPage());
